<template>
  <div class="zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">生产订单号</p>
            <div class="ipt">
              <Input type="text"
                     v-model="searchParams.orderCode"
                     clearable
                     :placeholder="`${$t('common.inputInfo')}`"
                     :maxlength="32"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">排程状态</p>
            <div class="ipt">
              <Select v-model="searchParams.state" clearable>
                <Option v-for="(item,index) of stateList" :value="item.code" :key="index">{{ item.desc }}</Option>
                <!-- <Option value="全部">全部</Option>
                <Option value="0">待下发</Option>
                <Option value="1">已下发</Option>
                <Option value="2">已排程</Option>
                <Option value="3">已派工</Option>
                <Option value="4">生产中</Option>
                <Option value="5">已完工</Option>
                <Option value="6">已暂停</Option>
                <Option value="7">关闭</Option> -->
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">计划类型</p>
            <div class="ipt">
              <Select v-model="searchParams.planType" clearable>
                <Option value="全部">全部</Option>
                <Option value="1">正常</Option>
                <Option value="2">返工</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">产出编码</p>
            <div class="ipt">
              <Input type="text"
                     v-model="searchParams.materialCode"
                     clearable
                     :placeholder="`${$t('common.inputInfo')}`"
                     :maxlength="32"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">车间产线</p>
            <div class="ipt">
              <Cascader clearable :data="orgList" v-model="searchParams.lineId"
                        :placeholder="`${$t('common.selectInfo')}`" change-on-select>
              </Cascader>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">BOM版本号</p>
            <div class="ipt">
              <Input type="text"
                     v-model="searchParams.bomVersion"
                     clearable
                     :placeholder="`${$t('common.inputInfo')}`"
                     :maxlength="32"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">创建人</p>
            <div class="ipt">
              <Select v-model="searchParams.createBy" clearable filterable  :remote-method="getCreateByListList">
                <Option v-for="(item,index) of createByList" :value="item.id" :key="index">{{ item.realname }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">创建时间</p>
            <div class="ipt">
              <DatePicker v-model="searchParams.createTime" placeholder="请选择" type="date"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">备注</p>
            <div class="ipt">
              <Input type="text"
                     v-model="searchParams.memo"
                     clearable
                     :placeholder="`${$t('common.inputInfo')}`"
                     :maxlength="32"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">是否委外</p>
            <div class="ipt">
              <Select v-model="searchParams.aaa" clearable>
                <Option :value="1" label="是"></Option>
                <Option :value="0" label="否"></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn" type="primary" @click="changeNum()">
                {{ $t("common.Query") }}
              </Button>
              <Button class="reset-btn" @click="reset()">
                {{ $t("common.reset") }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="alarmConfiguration">
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">生产订单</span>
          <Button @click="handleChange('add')">工单派工</Button>
          <Button @click="gongxuweiwai()">工序委外</Button>
          <Button @click="guanBi">关闭订单</Button>
          <Button @click="exportTemplateClick">{{ $t("common.Export")}}</Button>
        </div>
        <div class="tableContent">
          <Table class="resizable-table"
                 border
                 size="small"
                 highlight-row
                 @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,'orderAdjustmentDeviceInfo')}"
                 :columns="columns"
                 ellipsis
                 ref="selection"
                 stripe
                 :data="dataArr"
                 @on-selection-change="onSelectChange"
                 @on-row-click="rowClick">
          </Table>
        </div>
        <!-- 分页 -->
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="delIds.length"/>
          <Page :total="total"
                :page-size="pageSize"
                :page-size-opts="pageSizeOption"
                :current="pageNum"
                @on-change="changePageNum"
                @on-page-size-change="changePageSize"
                show-sizer
                show-total/>
        </div>
      </div>
      <div class="list-layout echart_Box mt16">
        <div class="btns clear">
          <span class="title">排程视图</span>
          <span style="margin-left: 10px" v-for="(item, index) in stateColor" :key="index">
            <span style="font-size: 14px">{{ item.label }}</span>
            <span style="width: 10px; height: 10px; margin-left: 8px" :style="'background:' + item.value"></span>
          </span>
        </div>
        <!--<Date-picker class="selectCy" style="width: 200px; font-size: 10px" type="daterange"></Date-picker>-->
        <div v-for="(item, index) in echartData" :key="index" class="one_line mt16">
          <Tooltip :content="item.deviceName">
            <div class="device_name">{{ item.deviceName }}:</div>
          </Tooltip>
          <div class="echart" v-if="loading===false">
            <oneLineChart :index="'oneLine' + index"
                          :mock="item.list"
                          :deviceCode="item.deviceCode"/>
          </div>
        </div>
        <div class="timeAxis">
          <span class="startTime">{{ startTime }}</span>
          <span class="endTime">{{ endTime }}</span>
        </div>
      </div>
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">已排程工单</span>
          <Button @click="distribute(true)">下发</Button>
          <Button @click="distribute(false)">撤回排程</Button>
          <Button @click="editOrder('edit')">修改</Button>
          <Button @click="delOrder">删除</Button>
        </div>
        <!-- 表格 -->
        <!-- @on-column-width-resize="onColumnWidthResize" -->
        <div class="tableContent">
          <Table class="resizable-table"
                 border
                 size="small"
                 @on-column-width-resize="onColumnWidthResize"
                 :columns="columnsK"
                 ellipsis
                 ref="selection"
                 stripe
                 :data="alData"
                 @on-selection-change="onSelectChange1">
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="viewNumble(row.orderCode)">查看物料用量</span>
            </template>
          </Table>
          <div class="pageWrap mt16">
            <pageLeftTitle :total="alTotal" :selected="delIds1.length"/>
            <Page :total="alTotal"
                  :page-size="alPageSize"
                  :page-size-opts="pageSizeOption"
                  :current="alPageNum"
                  @on-page-size-change="alChangePageSize"
                  @on-change="alChangePageNum"
                  show-sizer
                  show-total/>
          </div>
        </div>
      </div>
      <!-- 工单派工 -->
      <Modal :mask-closable="false"
             v-model="create"
             :title="diaStatus == 'edit' ? '编辑' : '工单派工'"
             class="modal-content-layout"
             width="80%">
        <div class="searchBox search-box-layout">
          <Form ref="form"
                class="formList"
                :model="formItem"
                label-position="top"
                :rules="ruleValidate">
            <Row :gutter="24">
              <Col span="6">
                <FormItem label="工单开始时间：" prop="workStartTime">
                  <DatePicker type="datetime"
                              format="yyyy-MM-dd HH:mm:ss"
                              :value="formItem.workStartTime"
                              placeholder="请选择工单开始时间："
                              :clearable="true"
                              name="sxbegdate"
                              @on-change="getbegdate"></DatePicker>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="工单结束时间：" prop="workEndTime">
                  <DatePicker type="datetime"
                              format="yyyy-MM-dd HH:mm:ss"
                              :value="formItem.workEndTime"
                              :clearable="true"
                              placeholder="请选择结束时间"
                              name="gqenddate"
                              @on-change="getenddate"></DatePicker>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="计划生产数量：">
                  <InputNumber style="width: 100%;" :min="0" disabled v-model="formItem.planProduceQuantity"></InputNumber>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="未派工数量：">
                  <InputNumber style="width: 100%;" :min="0" disabled
                               v-model="formItem.planProduceQuantity"></InputNumber>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
        <div class="tableContent">
          <Row :gutter="20" class="mt16">
            <Col span="12">
              <Table class="resizable-table"
                     border
                     size="small"
                     :columns="columns1"
                     ellipsis
                     highlight-row
                     ref="selection"
                     stripe
                     :data="moldList"
                     @on-row-click="onRowClick"></Table>
            </Col>
            <Col span="12">
              <!-- {{ rows }} -->
              <Table class="resizable-table"
                     border
                     size="small"
                     :columns="columns2"
                     ellipsis
                     ref="selection"
                     stripe
                     :row-key="deviceCode"
                     :data="deviceList"
                     @on-selection-change="dataClick">
                <template slot-scope="{ row,index1 }" slot="dispatchNum">
                  <InputNumber v-model="row.dispatchNum" :min="0" controls-outside
                               @on-change="tablePaiGongChange(row)"/>
                </template>
              </Table>
            </Col>
          </Row>
        </div>
        <div slot="footer">
          <Button type="default" @click="(create = false), (rows = {}), (selectRow = false)">
            {{ $t("common.Cancle") }}
          </Button>
          <!-- {{ diaStatus }} -->
          <Button type="primary" :loading="loading" @click="addOk('form')">{{ $t("maintenance.Confirmed") }}</Button>
        </div>
      </Modal>
      <!-- 查看物料用量 -->
      <Modal :mask-closable="false"
             v-model="viewNumbleDialog"
             title="库存分析"
             class="modal-title-layout"
             width="80%">
        <div class="list-layout mt16">
          <!-- 表格 -->
          <div class="tableContent">
            <Table
              class="resizable-table" border
              size="small"
              @on-column-width-resize="onColumnWidthResize"
              :columns="viewNumbleColumns"
              ellipsis
              ref="selection"
              stripe
              :data="inventoryAnalysisData"></Table>
          </div>
          <div class="pageWrap mt16">
            <pageLeftTitle :total="inventoryTotal"/>
            <Page :total="inventoryTotal"
                  :page-size="inventoryPageSize"
                  :page-size-opts="pageSizeOption"
                  :current="inventoryPageNum"
                  @on-page-size-change="inventoryChangePageSize"
                  @on-change="inventoryChangePageNum"
                  show-sizer
                  show-total/>
          </div>
        </div>
        <div slot="footer">
          <Button type="default" @click="viewNumbleDialog = false">{{ $t("common.Cancle") }}</Button>
          <Button type="primary" :loading="loading" @click="viewNumbleDialog = false">
            {{ $t("maintenance.Confirmed") }}
          </Button>
        </div>
      </Modal>
      <Modal :mask-closable="false"
             v-model="distributeView"
             :title="distributeTitle ? '下发确认' : '撤回排程'"
             class="modal-title-layout">
        <div class="icon blue" v-if="distributeTitle == true">
          <i class="iconfont zy-common-wancheng"></i>
        </div>
        <div class="icon red" v-else>
          <i class="iconfont zy-common-shanchu"></i>
        </div>
        <p class="title">
          <span v-if="distributeTitle === true">是否确认工单下发生产</span>
          <span v-else>是否撤回工单下发生产</span>
        </p>
        <div slot="footer">
          <Button type="default" @click="distributeView = false">{{$t("common.Cancle") }}</Button>
          <Button type="primary" :loading="loading" @click="distributeApi">{{$t("maintenance.Confirmed") }}</Button>
        </div>
      </Modal>
      <commonModal ref="commonModal"></commonModal>
    </div>
  </div>
</template>

<script>
  import {findOrgByToken} from "@/api/index.js";
  import {
    searchApi,
    getMoldList,
    add,
  } from "@/api/planManage/orderSchedul.js";
  import recursion from "@/util/recursion";
  import oneLineChart from "./moduls/oneLineChart.vue";
  import commonModal from "@/components/modalTypes/commonModal.vue";
  import fileDownload from "js-file-download";
  import toggleTableOperation from "@/mixins/toggleTableOperation";
  import RollingLoadSelect from './moduls/RollingLoadSelect.vue';

  export default {
    name: "productionPlan",
    components: {oneLineChart, commonModal,RollingLoadSelect},
    mixins: [toggleTableOperation],
    data() {
      return {
        createByList:[],
        orgList: [], //工厂名称
        searchParams: {
          state: '全部',
          planType: '全部'
        },
        pageNum: 1,
        pageSize: 5,
        total: 0,
        pageSizeOption: [5, 10, 20],
        columns: [
          {
            key: "checked",
            type: "selection",
            width: 60,
            align: "center"
          },
          {
            title: `${this.$t("common.index")}`,
            type: 'index',
            width: 100,
            align: 'center'
          },
          {
            title: "工序订单号",
            key: "orderCode",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "状态",
            key: "state",
            minWidth: 100,
            align: "center",
            resizable: true,
            render: (h, params) => {
              return h(
                "div",
                params.row.state === 0 ? '待排产'
                  : params.row.state === 1 ? '已排产'
                  : params.row.state === 2 ? '委外生产'
                    : params.row.state === 3 ? '已完成'
                            : params.row.state === 9? '关闭' : ''
                // params.row.state === 0 ? '待下发'
                //   : params.row.state === 1 ? '已下发'
                //   : params.row.state === 2 ? '已排程'
                //     : params.row.state === 3 ? '已派工'
                //       : params.row.state === 4 ? '生产中'
                //         : params.row.state === 5 ? '已完工'
                //           : params.row.state === 6 ? '已暂停'
                //             : params.row.state === 7 ? '关闭' : ''
              );
            },
          },
          {
            title: "生产订单号",
            key: "productionPlanNo",
            minWidth: 160,
            align: "center",
            resizable: true,
          },

          {
            title: "计划类型",
            key: "planType",
            minWidth: 100,
            align: "center",
            resizable: true,
            render: (h, params) => {
              return h(
                "div",
                params.row.planType === 1 ? '正常' : '返工'
              );
            },
          },
          {
            title: "工序名称",
            key: "procedureName",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "首次报工时间",
            key: "reportTime",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "累计天数",
            key: "days",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "产品编码",
            key: "productCode",
            minWidth: 160,
            align: "center",
            resizable: true
          },
          {
            title: "产出编码",
            key: "materialCode",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "计划数量",
            key: "planQuantity",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "批次",
            key: "batchNo",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "SNP",
            key: "snp",
            minWidth: 100,
            align: "center",
            resizable: true
          },
          {
            title: "计划开始时间",
            key: "planStartDate",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "计划结束时间",
            key: "planEndDate",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "是否委外",
            key: "aaa",//无字段
            minWidth: 160,
            align: "center",
            resizable: true,
            render: (h, params) => {
              return h(
                "div",
                params.row.aaa === 1 ? '是' : '否'
              );
            },
          },
          
          {
            title: "车间产线",
            key: "productionLocation",
            minWidth: 100,
            align: "center",
            resizable: true,
            tooltip:true,
          },
          {
            title: "备注",
            key: "memo",
            minWidth: 100,
            align: "center",
            resizable: true,
            tooltip: true,
          },
          {
            title: "创建人名称",
            key: "createName",
            minWidth: 160,
            align: "center",
            resizable: true
          },
          {
            title: "创建时间",
            key: "createTime",
            minWidth: 180,
            align: "center",
            resizable: true
          },
          {
            title: "更新人名称",
            key: "updateName",
            minWidth: 160,
            align: "center",
            resizable: true
          },
          {
            title: "更新时间",
            key: "updateTime",
            minWidth: 180,
            align: "center",
            resizable: true
          },
          {
            title: "计划SNP",
            key: "planSnp",
            minWidth: 180,
            align: "center",
            resizable: true
          },
          {
            title: "已派工数量",
            key: "dispatchQuantity",
            minWidth: 180,
            align: "center",
            resizable: true
          },
        ],
        dataArr: [],
        delIds: [],
        allCheck: false,
        orderCode: "",
        diaStatus: "",
        create: false,
        formItem: {
          workStartTime: "",
          workEndTime: "",
          planQuantity: null,
          planProduceQuantity: null,
        },
        ruleValidate: {
          workStartTime: [
            {
              required: true,
              message: "请选择开始时间",
              trigger: "blur"
            }
          ],
          workEndTime: [
            {
              required: true,
              message: "请选择结束时间",
              trigger: "blur"
            }
          ]
        },
        columns1: [
          {
            title: "工装BOM编号",
            key: "moldCode",
            width: 160,
            align: "center",
            resizable: true,
          },

          {
            title: "工装BOM名称",
            key: "moldName",
            width: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "工装BOM版本号",
            key: "version",
            width: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "件数",
            key: "bomCount",
            width: 90,
            align: "center",
            resizable: true,
          },
          {
            title: "备注",
            key: "remark",
            width: 110,
            align: "center",
            resizable: true,
            tooltip: true
          }
        ],
        moldList: [],
        moldListRow: {},
        columns2: [
          {
            key: "selection",
            type: "selection",
            width: 60,
            align: "center"
          },
          {
            title: "优先级",
            key: "priority",
            width: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "设备编号",
            key: "deviceCode",
            width: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "设备名称",
            key: "deviceName",
            width: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "工单数",
            key: "workOrderNumber",
            width: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "派工数量",
            slot: "dispatchNum",
            key: "dispatchNum",
            width: 240,
            align: "center",
            resizable: true,
          },
        ],
        deviceList: [],
        stateColor: [
          {
            label: "空闲",
            value: "#1db360" //绿色
          },
          {
            label: "已排程",
            value: "#f21d40" //绿色
          }
        ],
        echartData: [],
        startTime: null,
        endTime: null,
        columnsK: [
          {
            key: "selection",
            type: "selection",
            width: 60,
            align: "center"
          },
          {
            title: `${this.$t("common.index")}`,
            type: 'index',
            width: 100,
            align: 'center'
          },
          {
            title: "工单号",
            key: "workCode",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "工序名称",
            key: "productionProcesses",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "设备编号",
            key: "deviceCode",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "设备名称",
            key: "deviceName",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          // {
          //   title: "工序名称",
          //   key: "materialName",
          //   minWidth: 100,
          //   align: "center",
          //   resizable: true,
          // },
          {
            title: "工装BOM编号",
            key: "moldCode",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "工装BOM名称",
            key: "moldName",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "状态",
            key: "state",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "计划数量",
            key: "planProduceQuantity",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "提报数量",
            key: "reportedQuantity",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "生产数量",
            key: "produceQuantity",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "计划开始时间",
            key: "workStartTime",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "计划结束时间",
            key: "workEndTime",
            minWidth: 160,
            align: "center",
            resizable: true,
          },
          {
            title: "排产人",
            key: "handProduceMan",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          // {
          //   title: "创建时间",
          //   key: "createTime",
          //   minWidth: 100,
          //   align: "center",
          //   resizable: true,
          // },
          {
            title: "下发人",
            key: "distributeMan",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "下发时间",
            key: "distributeTime",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "操作",
            slot: "action",
            fixed: "right",
            minWidth: 120,
            align: "center"
          }
        ],
        alData: [],
        alPageNum: 1,
        alPageSize: 10,
        alTotal: 0,
        delIds1: [],
        viewNumbleDialog: false,
        inventoryMaterialCode: '',
        inventoryPageNum: 1,
        inventoryPageSize: 5,
        inventoryTotal: 0,
        viewNumbleColumns: [
          {
            title: "序号",
            type: "index",
            width: 80,
            align: "center"
          },
          {
            title: "物料编号",
            key: "materialCode",
            minWidth: 60,
            align: "center",
            resizable: true,
          },

          {
            title: "物料名称",
            key: "materialName",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "物料类别",
            key: "materialType",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "需求数量",
            key: "needQuantity",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "计量单位",
            key: "unit",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "材料牌号",
            key: "materialMark",
            minWidth: 100,
            align: "center",
            resizable: true,
          },
          {
            title: "是否替代料",
            key: "isReplaceMaterial",
            minWidth: 100,
            align: "center",
            resizable: true,
          }
        ],
        inventoryAnalysisData: [],
        distributeView: false,
        distributeTitle: "",
        loading: false,
        selectRow: false,
        rows: {},
        stateList:[],
      };
    },
    mounted() {
      this.getTableColumnsWidth(this.columns, "orderAdjustmentDeviceInfo");
      this.getTableColumnsWidth(this.columnsK);
      this.getOrgList();
      this.searchList();
      this.getStateList();
    },
    methods: {
      gongxuweiwai(){
        console.log(111);
        if (this.delIds.length!==1) {
           this.$Message.error({
              content: "请选择一条数据",
              duration: 6,
              closable: true
            });
          return
        }
        this.axios({
          method:'put',
          url: '/dms/order/orderOutsourcing',
          params: {
            id: this.delIds[0].id
          }
        }).then(res=>{
          if (res.code==200) {
               this.$Message.success({
              content: res.msg,
              duration: 6,
              closable: true
            });
            this.getAlList();
          }else{
               this.$Message.error({
              content: res.msg,
              duration: 6,
              closable: true
            });

          }
        })
      },
      refresh() {
        this.getEchartData();
        this.searchList();
        this.getAlList();
        this.rows = [];
      },
      getCreateByListList(val) {
        this.axios({
          method: "get",
          url: "/dms/user/userList",
          params: {
            key: val
          },
        }).then(res => {
          if (res.code === 200) {
            this.createByList = res.data;
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      // 计划状态
      getStateList() {
        this.axios({
          method: "get",
          url: "/dms/common/orderStateList",

        }).then(res => {
          if (res.code === 200) {
           this.stateList = res.data
          }
        });
      },
      //车间产线
      getOrgList() {
        let params = {
          level: 0
        };
        findOrgByToken(params).then(res => {
          if (res.code === 200) {
            const obj = {
              label: "name",
              value: "id",
              children: "children"
            };
            this.orgList = recursion.convertTree(res.data, obj);
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      reset() {
        this.searchParams = {
          state: '全部',
          planType: '全部'
        };
        this.changeNum();
      },
      //分页
      changeNum() {
        this.pageNum = 1;
        this.delIds = [];
        this.searchList();
      },
      changePageSize(pageSize) {
        this.pageSize = pageSize;
        this.searchList();
      },
      changePageNum(val) {
        this.pageNum = val;
        this.searchList();
      },
      //查询列表
      searchList() {
        let params = {
          ...this.searchParams,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        if (params['state'] === '全部') {
          params['state'] = '';
        }
        if (params['planType'] === '全部') {
          params['planType'] = '';
        }
        if (this.searchParams.lineId && this.searchParams.lineId.length > 0) {
          params['lineId'] = this.searchParams.lineId[this.searchParams.lineId.length - 1];
        } else {
          params['lineId'] = "";
        }
        searchApi(params).then(res => {
          if (res.code === 200) {
            this.dataArr = res.data.list;
            this.total = res.data.total;
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      onSelectChange(selection) {
        let myArray = [];

        selection.map((item) => {
          myArray.push(item);
        });
        this.delIds = myArray;
        if (selection.length > 0) {
          this.allCheck = true;
        } else {
          this.allCheck = false;
        }
      },
      rowClick(row) {
        this.orderCode = row.orderCode;
        this.delIds1 = [];
        this.getEchartData();
        this.getAlList();
      },
      //工单派工
      handleChange(status) {
        this.diaStatus = status;
        if (this.delIds.length !== 1) {
          this.$Message.warning({
            content: "只能选择一条数据",
            duration: 6,
            closable: true
          });
          return;
        }
        this.create = true;
        this.deviceList = [];
        this.moldListRow = [];
        this.formItem = {
          workStartTime: "",
          workEndTime: "",
          planQuantity: null,
          planProduceQuantity: null,
        };
        if (this.delIds[0].planQuantity || this.delIds[0].planQuantity !== 0) {
          this.formItem['planQuantity'] = this.delIds[0].planQuantity;
        }
        if ((this.delIds[0].planQuantity || this.delIds[0].planQuantity >= 0) && (this.delIds[0].dispatchQuantity  || this.delIds[0].dispatchQuantity  >= 0)) {
          this.formItem['planProduceQuantity'] = this.delIds[0].planQuantity - this.delIds[0].dispatchQuantity ;
        }
        this.rows = [];
        this.axios({
          method: "get",
          url: "/dms/order/material/bom",
          params: {
            materialCode: this.delIds[0].materialCode
          }
        }).then(res => {
          if (res.code === 200) {
            this.moldList = res.data;
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      onRowClick(row) {
        this.moldListRow = row;
        this.rows = [];
        this.axios({
          method: "get",
          url: "/dms/order/mold/device",
          params: {
            moldCode: row.moldCode
          }
        }).then(res => {
          if (res.code === 200) {
            let deviceList = res.data;
            for (let i = 0; i < deviceList.length; i++) {
              deviceList[i]['dispatchNum'] = null;
            }
            this.deviceList = deviceList.concat();
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      tablePaiGongChange(row) {
        let index = row._index;
        this.deviceList[index]['dispatchNum']=row['dispatchNum'];
        let count = 0;
        for (let i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i]['dispatchNum']) {
            count = count + this.deviceList[i]['dispatchNum'];
          }
        }
        for(let i=0;i<this.deviceList.length;i++){
          for(let j=0;j<this.rows.length;j++){
            if(this.rows[j].deviceCode===this.deviceList[i].deviceCode){
              this.rows[j].dispatchNum=this.deviceList[i].dispatchNum;
              this.deviceList[i]._checked=true;
            }
          }
        }
        if (count > this.formItem.planProduceQuantity) {
          this.$Message.warning({
            content: '派工数量总和不能大于未派工数量',
            duration: 6,
            closable: true
          });
        }
        console.log(this.deviceList);
      },
      getbegdate(val) {
        this.formItem.workStartTime = val;
        this.formItem.workEndTime = this.$moment(new Date(val)).add(7, 'days').format("YYYY-MM-DD HH:mm:ss")
        if (this.formItem.workStartTime && this.formItem.workEndTime) {
          if (this.$moment(this.formItem.workEndTime).diff(this.$moment(this.formItem.workStartTime)) < 0) {
            this.$Message.warning({
              content: '工单开始时间不能在工单结束时间',
              duration: 6,
              closable: true
            });
            this.formItem.workStartTime = null;
          }
        }
      },
      getenddate(val) {
        this.formItem.workEndTime = val;
        if (this.formItem.workStartTime && this.formItem.workEndTime) {
          if (this.$moment(this.formItem.workEndTime).diff(this.$moment(this.formItem.workStartTime)) < 0) {
            this.$Message.warning({
              content: '工单开始时间不能在工单结束时间',
              duration: 6,
              closable: true
            });
            this.formItem.workEndTime = null;
          }
        }
      },
      dataClick(selection) {
        this.rows = selection.concat();
        for (let i = 0; i < this.deviceList.length; i++) {
          this.deviceList[i]['dispatchNum'] = null;
          this.deviceList[i]._checked=false;
        }
        let dispatchNum =Number((this.formItem.planProduceQuantity / this.rows.length).toFixed(2));
        for(let i=0;i<this.deviceList.length;i++){
          for(let j=0;j<this.rows.length;j++){
            if(this.rows[j].deviceCode===this.deviceList[i].deviceCode){
              this.deviceList[i].dispatchNum=dispatchNum;
              this.rows[j].dispatchNum=dispatchNum;
              this.deviceList[i]._checked=true;
            }
          }
        }
      },
      //关闭
      guanBi() {
        if (this.delIds.length !== 1) {
          this.$Message.warning({
            content: "只能选择一条数据",
            duration: 6,
            closable: true
          });
          return false;
        }
        this.axios({
          method: "get",
          url: "/dms/order/close",
          params: {
            orderCode: this.delIds[0].orderCode
          }
        }).then(res => {
          if (res.code === 200) {
            this.selectRow = false;
            this.orderCode=this.delIds[0].orderCode;
            this.delIds1 = [];
            this.delIds = [];

            this.refresh();
            this.$Message.success({
              content: "关闭成功",
              duration: 6,
              closable: true
            });
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      //导出
      exportTemplateClick() {
        const filName = "工单台账";
        let params = {
          ...this.searchParams,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        if (params['state'] === '全部') {
          params['state'] = '';
        }
        if (params['planType'] === '全部') {
          params['planType'] = '';
        }
        this.axios({
          method: "get",
          url: "/dms/order/export",
          params: params,
          responseType: "blob"
        }).then(res => {
          fileDownload(res, filName + ".xlsx");
        });
      },
      //排程视图
      getEchartData() {
        this.loading = true;
        this.axios({
          method: "get",
          url: "/dms/order/produce/view",
          params: {
            orderCode: this.orderCode
          }
        }).then(res => {
          if (res.code === 200) {
            this.$set(this, "echartData", res.data);
            if (res.data.length > 0) {
              this.startTime = this.$moment(res.data[0].list[0].startTime).format(
                "YYYY-MM-DD HH:mm"
              );
              this.endTime = this.$moment(
                res.data[0].list[res.data[0].list.length - 1].endTime
              ).format("YYYY-MM-DD HH:mm");
            }
            this.$forceUpdate();
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
          this.loading = false;
        });
      },
      //已排程工单
      getAlList() {
        let params = {
          pageNum: this.alPageNum,
          pageSize: this.alPageSize,
          orderCode: this.orderCode,
        };
        this.axios({
          method: "get",
          url: "dms/productionWork/arrangedWorkList",
          params
        }).then(res => {
          if (res.code === 200) {
            this.alData = res.data.records;
            this.alTotal = res.data.total;
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      alChangePageNum(val) {
        this.alPageNum = val;
        this.getAlList();
      },
      alChangePageSize(pageSize) {
        this.alPageSize = pageSize;
        this.getAlList();
      },
      onSelectChange1(selection) {
        this.delIds1 = JSON.parse(JSON.stringify(selection));
      },
      delOrder() {
        const data = this.delIds1.map(item => item.id);
        if (data.length === 0) {
          this.$Message.warning({
            content: "至少选择一条已排程工单",
            duration: 6,
            closable: true
          });
          return;
        }
        this.$refs.commonModal.showModal({
          type: "delete",
          title: "删除提醒",
          desc: "确认是否删除",
          submit: () => {
            this.axios({
              method: "delete",
              url: "/dms/order/remove",
              data: data
            }).then(res => {
              if (res.code === 200) {
                this.$Message.success(res.msg);
                this.delIds1 = [];
                this.refresh();
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          }
        });
      },
      //查看物料用量
      viewNumble(orderCode) {
        this.inventoryMaterialCode = orderCode;
        this.getInventoryList();
      },
      getInventoryList() {
        let params = {
          pageNum: this.inventoryPageNum,
          pageSize: this.inventoryPageSize,
          orderCode: this.inventoryMaterialCode
        };
        this.axios({
          method: "get",
          url: "/dms/order/material/consumption",
          params: params
        }).then(res => {
          if (res.code === 200) {
            this.inventoryAnalysisData = res.data.records;
            this.inventoryTotal = res.data.total;
            this.viewNumbleDialog = true;
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
      inventoryChangePageSize(pageSize) {
        this.inventoryPageSize = pageSize;
        this.getInventoryList();
      },
      inventoryChangePageNum(val) {
        this.inventoryPageNum = val;
        this.getInventoryList();
      },
      //下发,撤回
      distribute(status) {
        if (this.delIds1.length < 1) {
          this.$Message.warning({
            content: "只能选择一条数据",
            duration: 6,
            closable: true
          });
          return;
        }
        this.distributeTitle = status;
        this.distributeView = true;
      },
      distributeApi() {
        let myArray = [];
        this.delIds1.map((item) => {
          myArray.push(item.id);
        });
        if (this.distributeTitle) {
          this.axios({
            method: "PUT",
            url: '/dms/order/issue',
            data: myArray
          }).then(res => {
            if (res.code === 200) {
              this.distributeView = false;
              this.$Message.success({
                content: res.msg,
                duration: 6,
                closable: true
              });
              this.delIds1 = [];
              this.refresh();
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true
              });
            }
          });
        } else {
          this.axios({
            method: "put",
            url: '/dms/order/recall',
            data: [myArray[0]]
          }).then(res => {
            if (res.code === 200) {
              this.distributeView = false;
              this.$Message.success({
                content: res.msg,
                duration: 6,
                closable: true
              });
              this.delIds1 = [];
              this.refresh();
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true
              });
            }
          });
        }
      },
      addOk(name) {
        if ((!Array.isArray(this.rows))||this.rows.length === 0) {
          this.$Message.warning({
            content: "请选择一条数据",
            duration: 6,
            closable: true
          });
          return;
        }
        let count = 0;
        for (let i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i]['dispatchNum']) {
            count = count + this.deviceList[i]['dispatchNum'];
          }
        }
        if (count > this.formItem.planProduceQuantity) {
          this.$Message.warning({
            content: '派工数量总和不能大于未派工数量',
            duration: 6,
            closable: true
          });
          return;
        }
        this.$refs[name].validate(valid => {
          if (!valid) {
            return;
          }
          this.loading = true;
          let data = {};
          if (this.diaStatus === "add") {
            let dispatchDeviceList = [];
            for (let i = 0; i < this.rows.length; i++) {
              let obj = {
                deviceCode: this.rows[i].deviceCode,
                dispatchNum: Number(this.rows[i].dispatchNum),
              };
              dispatchDeviceList.push(obj);
            }
            data = {
              orderCode: this.delIds[0].orderCode,
              moldCode: this.moldListRow.moldCode,
              version: this.moldListRow.version,
              planStartDateTime: this.formItem.workStartTime,
              planEndDateTime: this.formItem.workEndTime,
              dispatchDeviceList: dispatchDeviceList
            };
            this.axios({
              method: "post",
              url: "/dms/order/dispatch",
              data: data
            }).then(res => {
              if (res.code === 200) {
                this.loading = false;
                this.selectRow = false;
                this.orderCode=this.delIds[0].orderCode;
                this.delIds1 = [];
                this.delIds = [];

                this.create = false;
                this.refresh();
                this.$refs.form.resetFields();
                this.$Message.success({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              } else {
                this.loading = false;
                this.selectRow = true;
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          } else {
            data = {
              ...this.formItem,
              id: this.delIds1[0].id,
              orderCode: this.delIds1[0].orderCode,
              moldCode: this.moldListRow.moldCode?this.moldListRow.moldCode:'',
              version: this.moldListRow.version?this.moldListRow.version:'',
              deviceCode: this.rows[0].deviceCode?this.rows[0].deviceCode:''
            };
            if (this.delIds1[0].workOrderGroup) {
              data.workOrderGroup = this.delIds1[0].workOrderGroup;
            }
            this.axios({
              method: "post",
              url: "/dms/order/modify",
              data: data
            }).then(res => {
              if (res.code === 200) {
                this.loading = false;
                this.selectRow = false;
                this.delIds1 = [];
                this.delIds = [];

                this.create = false;
                this.refresh();
                this.$refs.form.resetFields();
                this.$Message.success({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              } else {
                this.loading = false;
                this.selectRow = true;
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          }
        });
      },
      // 编辑
      editOrder(status) {
        const delIds1 = JSON.parse(JSON.stringify(this.delIds1));
        this.diaStatus = status;
        if (delIds1.length !== 1) {
          this.$Message.warning({
            content: "只能选择一条数据",
            duration: 6,
            closable: true
          });
          return;
        }
        this.formItem.planProduceQuantity = null;
        this.formItem = {
          ...delIds1[0]
        };
        this.create = true;
        this.axios({
          method: "get",
          url: "/dms/order/material/bom",
          params: {
            materialCode: delIds1[0].materialCode
          }
        }).then(res => {
          if (res.code === 200) {
                this.moldList = res.data;
                this.deviceList = [];
                this.create = true;
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      },
    }
  };
</script>

<style scoped lang="scss">
  .one_line {
    display: flex;
    flex-direction: row;

    .device_name {
      width: 90px;
      padding: 0 0 0 10px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }

    .echart {
      flex: 1;
      margin-left: 10px;
    }
  }

  .echart_Box {
    position: relative;
    min-height: 200px;
  }

  .timeAxis {
    line-height: 25px;
  }

  .startTime {
    font-size: 12px;
    color: #333333;
    margin-left: 25px;
  }

  .endTime {
    font-size: 12px;
    color: #333333;
    float: right;
  }

  .selectCy {
    position: absolute;
    top: 18px;
    left: 100px;
  }
</style>
